package com.example.radioplayer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore.Audio.Media;
import android.util.Log;

public class MusicLoader {
	/**
	 * 此类采用单例模式，通过instance()方法获得唯一的对象。 getMusicList()方法是向外界开放的借口，返回音乐资源。
	 * 其中返回的是是一个专辑列表，List<Ablum>,每个ablum对象是包含多个Music对象。
	 * getMusicLibary()方法可以返回MusicLibary对象
	 * 
	 * */

	private static final String TAG = MusicLoader.class.getName();

	private  MusicLibary musicLibary = new MusicLibary() ;
	

	private static MusicLoader mMusicLoader;

	private static ContentResolver mContentResolver;

	private Uri contentUri = Media.EXTERNAL_CONTENT_URI;

	private String[] projection = { Media._ID, Media.TITLE, Media.DATA,
			Media.ALBUM, Media.ARTIST, Media.DURATION, Media.SIZE };

	private String where = "mime_type in ('audio/mpeg','audio/x-ms-wma') and bucket_display_name <> 'audio' and is_music > 0 ";
	private String sortOrder = Media.DATA;

	public static MusicLoader instance(ContentResolver contentResolver) {
		if (mMusicLoader == null) {
			mContentResolver = contentResolver;
			mMusicLoader = new MusicLoader();
		}
		return mMusicLoader;
	}

	/**
	 * 在此构造函数中，查到到sdcard中所有的音乐资源，并按照ablum类别存储在List中
	 * */
	private MusicLoader() {
		Cursor cursor = mContentResolver.query(contentUri, null, null, null,
				null);
		if (cursor == null) {
			Log.v(TAG, "Music Loader cursor == null. ");
		} else if (!cursor.moveToFirst()) {
			Log.v(TAG, "Music Loader cursor.moveToFirst() return false");
		} else {
			int displayNameCol = cursor.getColumnIndex(Media.TITLE);
			int albumCol = cursor.getColumnIndex(Media.ALBUM);
			int idCol = cursor.getColumnIndex(Media._ID);
			int durationCol = cursor.getColumnIndex(Media.DURATION);
			int sizeCol = cursor.getColumnIndex(Media.SIZE);
			int artistCol = cursor.getColumnIndex(Media.ARTIST);
			int urlCol = cursor.getColumnIndex(Media.DATA);
			do {
				Ablum ablum;
				String url = cursor.getString(urlCol);
				String albumName = cursor.getString(albumCol);
				if (!musicLibary.ablumIsExist(albumName)) {
					ablum = new Ablum();
					ablum.name = albumName;
					String coverUrl = findCoverUrl(url, albumName);
					ablum.coverUrl = coverUrl;
					ablum.cover = BitmapFactory.decodeFile(coverUrl);
					musicLibary.ablums.add(ablum);

				} else {
					ablum = musicLibary.findAblum(albumName);
				}
				String title = cursor.getString(displayNameCol);
				Music music;
				long id = cursor.getLong(idCol);
				int duration = cursor.getInt(durationCol);
				long size = cursor.getLong(sizeCol);
				String artist = cursor.getString(artistCol);
				String fileName = getFileName(url);

				if (!ablum.musicIsExist(title)) {
					music = new Music();
					setMusicInfo(albumName, title, music, id, duration, artist,
							fileName, url);
					ablum.musics.add(music);
				} else {
					music = ablum.findMusic(fileName);
					// setMusicInfo(albumName, title, music, id, duration,
					// artist,fileName);
				}

			} while (cursor.moveToNext());
		}

	}

	private void setMusicInfo(String albumName, String title, Music music,
			long id, int duration, String artist, String fileName, String url) {
		music.url = url;
		music.ablum = albumName;
		music.artist = artist;
		music.duration = duration;
		music.fileName = fileName;
		music.id = id;
		music.title = title;
	}

	private String getFileName(String filePath) {
		return filePath.substring(filePath.lastIndexOf("/") + 1,
				filePath.lastIndexOf(".") - 1);
	}

	/**
	 * 根据歌曲文件名称，在相同的文件夹内，寻找相同名称的图片
	 * 
	 * @param 歌曲文件完整的URI
	 * @return 图片文件完整的URI
	 * */
	private String findCoverUrl(String filePath, String albumName) {
		String pathName = filePath.substring(0, filePath.lastIndexOf("/") + 1);
		String fileName = pathName + albumName;
		String[] fileUrls = { fileName + ".jpg", fileName + ".png",
				fileName + ".jpeg" };
		for (String url : fileUrls) {
			File file = new File(url);
			if (file.isFile()) {
				return url;
			}
		}
		return null;
	}

	/**
	 * 与外界接口，通过此函数获得音乐资源
	 * */
	public List<Ablum> getMusicList() {
		return musicLibary.ablums;
	}

	public MusicLibary getMusicLibary() {
		return musicLibary;
	}


	/**
	 * 以下三个类是javabean，MusicsLibary用来存放整个sdcard里面的所有音频文件信息。
	 * Ablum存放的是专辑的名称
	 * Music存放单曲信息
	 * */
	
	public class MusicLibary {

		public List<Ablum> ablums = new ArrayList<Ablum>();

		public boolean ablumIsExist(String ablumName) {
			for (Ablum ablum : ablums) {
				if (ablum.name.equals(ablumName)) {
					return true;
				}
			}
			return false;
		}

		public Ablum findAblum(String ablumName) {
			for (Ablum ablum : ablums) {
				if (ablum.name.equals(ablumName)) {
					return ablum;
				}
			}
			return null;
		}

		@Override
		public String toString() {
			return "Musics []";
		}

	}
	
	public class Ablum {
		String name;
		public List<Music> musics = new ArrayList<Music>();
		public String coverUrl;
		public Bitmap cover;

		// 通过音乐标标题，判断此音乐在不在此专辑中
		public boolean musicIsExist(String musicName) {
			for (Music music : musics) {
				if (music.title.equals(musicName)) {
					return true;
				}
			}
			return false;
		}

		// 通过音乐名称找到此音乐
		public Music findMusic(String musicName) {
			for (Music music : musics) {
				if (music.title.equals(musicName)) {
					return music;
				}
			}
			return null;
		}

		@Override
		public String toString() {
			return "Ablum [name=" + name + "]";
		}

	}

	
	
	public class Music {
		public String fileName;
		public long id;
		public String title;
		public int duration;
		public String artist;
		public String url;
		public String ablum;
		public String coverUrl;
		public Bitmap cover;

		@Override
		public String toString() {
			return "Music [fileName=" + fileName + ", id=" + id + ", title="
					+ title + ", duration=" + duration + ", artist=" + artist
					+ ", url=" + url + ", ablum=" + ablum + ", coverUrl="
					+ coverUrl + ", cover=" + cover + "]";
		}

	}

	

}
